package erlwitch;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import erlwitch.parser.Parser;
import erlwitch.parser.ParserException;
import erlwitch.parser.structure.Module;

public class Main {

	/**
	 * Runs the scanner on input files.
	 * 
	 * This is a standalone scanner, it will print any unmatched text to
	 * System.out unchanged.
	 * 
	 * @param argv
	 *            the command line, contains the filenames to run the scanner
	 *            on.
	 */
	public static void main(String argv[]) {
		if (argv.length == 0) {
			System.out.println("Usage : java Lexer <inputfile>");
		} else {
			List<Module> mods = new ArrayList<Module>();
			for (int i = 0; i < argv.length; i++) {
				List<Module> ms = parseDir(argv[i]);
				mods.addAll(ms);
			}
			System.out.println("Modules: " + mods.size());
			int cant = 0;
			for (Module m: mods) {
				cant += m.getFunList().size();
			}
			System.out.println("Functions: " + cant);
		}
	}
	
	private static List<Module> parseDir(String strDir) {
		List<Module> ret = new ArrayList<Module>();
		File d = new File(strDir);
		if (d.exists() && d.isDirectory()) {
			File[] children = d.listFiles();
			for (File f: children) {
				String[] name = f.getName().split("\\.");
				if (name.length > 1) {
					String extension = name[name.length-1];
					if (extension.equalsIgnoreCase("erl") || extension.equalsIgnoreCase("hrl")) {
						if (extension.equalsIgnoreCase("erl")) {
							Module m;
							try {
								m = Parser.parseFile(f.getPath());
								ret.add(m);
							} catch (ParserException e) {
								// TODO Auto-generated catch block
								System.out.println("Exception on: " + f.getName());
								e.printStackTrace();
							}
						}
					}
				}
			}
		}
		return ret;
	}

}
